﻿using System;
using System.Text;
using System.Xml;
using System.IO;
using System.IO.Packaging;
using Microsoft.XmlDiffPatch;

namespace OPCDiffCore.XML
{
    internal class XmlAnalyzer : PartAnalyzer
    {
        internal override PartDiff Analyze(PackagePart originalPart, PackagePart diffPart, AnalyzeLevel level)
        {
            PartDiff retPartDiff = new PartDiff(originalPart.Uri, originalPart.ContentType);

            // Store the XML changes structure
            MemoryStream changeStream = new MemoryStream();

            // Compare both XML files and make the XMLDiff patch
            XmlDiff xmlDiff = new XmlDiff(XmlDiffOptions.IgnoreComments |
                XmlDiffOptions.IgnoreDtd |
                XmlDiffOptions.IgnoreXmlDecl);
            xmlDiff.Algorithm = XmlDiffAlgorithm.Fast;
            bool compRes = xmlDiff.Compare(XmlReader.Create(originalPart.GetStream()),
                XmlReader.Create(diffPart.GetStream()),
                XmlWriter.Create(changeStream));

            if (compRes)
            {
                switch (level)
                {
                    case AnalyzeLevel.Logical:
                        // Put the cursor at the beginning in order to read the stream
                        //changeStream.Seek(0, SeekOrigin.Begin);

                        //XmlDocument xmlChangeDoc = new XmlDocument();
                        //XmlNamespaceManager nsManager = new XmlNamespaceManager(xmlChangeDoc.NameTable);
                        //nsManager.AddNamespace("xd", "http://schemas.microsoft.com/xmltools/2002/xmldiff");
                        //xmlChangeDoc.Load(changeStream);

                        //using (Stream s = new FileStream("outXMLDiff.txt", FileMode.OpenOrCreate))
                        //{
                        //    XmlTextWriter xmltw = new XmlTextWriter(s, Encoding.UTF8);
                        //    xmltw.Formatting = Formatting.Indented;
                        //    xmlChangeDoc.Save(xmltw);
                        //}

                        // TODO : Build changes
                        break;

                    case AnalyzeLevel.QuickLogical:
                        retPartDiff.DiffType = DiffType.Modified;
                        retPartDiff.Add(
                            new DiffElement(DiffType.Modified, DiffElementType.XmlContent,
                                "The XML content has been changed !"));
                        break;
                }
            }

            return retPartDiff;
        }
    }
}
